﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage.Streams;

namespace LightOMator.IO
{
    static class StreamSocketExtensions
    {
        public static async Task WriteString(this StreamSocket socket, string text)
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
            IBuffer buffer = data.AsBuffer();
            await socket.OutputStream.WriteAsync(buffer);
            await socket.OutputStream.FlushAsync();
        }

        public static async Task<string> ReadString(this StreamSocket socket)
        {
            DataReader reader = new DataReader(socket.InputStream);
            await reader.LoadAsync(4);
            int length = reader.ReadInt32();
            await reader.LoadAsync((uint)length);
            string result = reader.ReadString((uint)length);
            return result;
        }
    }
}
